<template>
	<view class="container">
		<view class="edit-bar">
			<text class="edit-btn" @click="toggleEdit">{{isEditing ? '完成' : '编辑'}}</text>
		</view>

		<!-- 空白页 -->
		<view v-if="!hasLogin || empty===true" class="empty">
			<image src="/static/emptyCart.jpg" mode="aspectFit"></image>
			<view v-if="hasLogin" class="empty-tips">
				空空如也
				<navigator class="navigator" v-if="hasLogin" url="../index/index" open-type="switchTab">随便逛逛>
				</navigator>
			</view>
			<view v-else class="empty-tips">
				空空如也
				<view class="navigator" @click="navToLogin">去登陆></view>
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view v-for="(brand, brandIndex) in cartList" :key="brandIndex" class="cart-item">
				<view class="i-top b-b">
					<text class="shop-name">{{brand.name}}</text>
				</view>

				<view class="goodsview">
					<view v-for="(goods, goodsIndex) in brand.dtsCart" :key="goodsIndex" class="goods-item">
						<view class="goods-checkbox" :class="{checked: goods.checked}"
							@click="check('goods', brandIndex, goodsIndex)"></view>
						<image class="goods-img" :src="goods.picUrl" style="width: 100px; height: 100px;"></image>
						<view class="goods-info">
							<text class="goods-name">{{goods.goodsName}}</text>
							<view class="price-and-num">
								<text>￥{{goods.price}}</text>
								<view class="num-container">
									<!-- 正常模式显示 -->
									<text v-if="!isEditing" class="static-num">x{{goods.number}}</text>
									<!-- 编辑模式显示 -->
									
									<view v-else class="number-box">
									    <view class="jian" @click="decreaseQuantity(goods.id)"> - </view>
									    <input 
									        type="number" 
									        :value="goods.number" 
									        min="1" 
									        class="quantity-input" 
									        @input="onQuantityInput($event, goods.id)"
									        @blur="handleInputQuantity($event, goods.id)"
									    >
									    <view class="jia" @click="increaseQuantity(goods.id)"> + </view>
									</view>
									
						
								</view>
								

							</view>
						</view>

					</view>
				</view>
			</view>


			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="left-group">
					<view class="checkbox">
						<image :src="allChecked?'/static/selected.png':'/static/select.png'" mode="aspectFit"
							@click="check('all')"></image>
						<text class="select-all">全选({{selectedCount}})</text>
					</view>

					<view v-if="!isEditing" class="total-box">
						<!-- 原有价格显示 -->
						<text class="price">¥{{total}}</text>
					</view>

					<view v-if="isEditing" class="batch-delete" @click="batchDelete">
						删除({{selectedCount}})
					</view>
				</view>

				<button v-if="!isEditing" class="confirm-btn" @click="createOrder">去结算</button>
				<button v-else class="confirm-btn" @click="toggleEdit">完成</button>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue';
	import {
		getCartList,
		getCartUpdate,
		getDeleted
	} from '@/config/api/cart.js';

	export default {
		components: {
			uniNumberBox
		},
		computed: {
		    ...mapState(['userInfo'])
		  },
		data() {
			return {
				isEditing: false,
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				hasLogin:null
			};
		},
		onLoad() {
			this.loadData();
		},
		onShow() {
			// 从其他页面返回时重新查询（可选需求）
			// 检查登录状态
			  this.hasLogin = this.$store.state.hasLogin;
			  
			  // 如果已登录且用户信息存在，加载数据
			  if (this.hasLogin && this.userInfo.id) {
			    this.loadData();
			  }
		},
		watch: {
			//显示空白页
			cartList(e) {
				let empty = e.length === 0 ? true : false;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			},

		},
		computed: {
			...mapState(['hasLogin', 'userInfo']),
			// 计算是否有选中商品
			hasCheckedItems() {
				return this.cartList.some(brand =>
					brand.dtsCart.some(goods => goods.checked)
				)
			},
			selectedCount() {
				return this.cartList.reduce((total, brand) => {
					return total + brand.dtsCart.filter(goods => goods.checked).length
				}, 0)
			}
		},
		methods: {
			//请求数据
			async loadData() {
				//查询购物车中的数据
				if (!this.userInfo || !this.userInfo.id) {
				    console.log('用户信息未获取');
				    return;
				  }
				try {
					const userId = this.userInfo.id;
					console.log("userid+sss"+userId);
					const res = await getCartList({
						userId
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.cartList = res.data.data.map(brand => ({
						  ...brand,
						  dtsCart: brand.dtsCart.map(goods => ({
						    ...goods,
						    id: goods.id, // 确保id存在且正确
						    number: goods.number,
						    checked: goods.checked || false
						  }))
						}));
						this.calcTotal(); //计算总价
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			// 新增编辑切换方法
			toggleEdit() {
				this.isEditing = !this.isEditing
				if (!this.isEditing) {
					// 退出编辑模式时同步数据
					this.calcTotal()
				}
			},
			
			// 批量删除选中商品
			async batchDelete() {
				// 收集选中的商品ID
				const selectedIds = [];
				this.cartList.forEach(brand => {
					brand.dtsCart.forEach(goods => {
						if (goods.checked) {
							selectedIds.push(goods.id);
						}
					});
				});
	
				if (selectedIds.length === 0) {
					this.$api.msg('请选择要删除的商品');
					return;
				}
	
				uni.showModal({
					content: `确定删除选中的${selectedIds.length}件商品？`,
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '正在删除'
							});
							try {
								// 调用删除接口
								const res = await getDeleted({
									ids: encodeURIComponent(JSON.stringify(selectedIds))
								});
								uni.hideLoading();
								if (res.data.code === 200) {
									this.$api.msg('删除成功');
									// 重新加载购物车
									this.loadData();
									// 退出编辑模式
									this.isEditing = false;
								} else {
									this.$api.msg(res.data.msg || '删除失败');
								}
							} catch (error) {
								uni.hideLoading();
								this.$api.msg('请求失败');
							}
						}
					}
				});
			},


			navToLogin() {
				uni.navigateTo({
					url: '/pages/public/login'
				})
				this.hasLogin = true;
			},
			//选中状态处理
			check(type, index, goodsIndex) {
				if (type === 'brand') {
					// 切换整个品牌选中状态
					const checked = !this.cartList[index].checked;
					this.cartList[index].checked = checked;
					this.cartList[index].dtsCart.forEach(item => {
						item.checked = checked;
					});
				} else if (type === 'goods') {
					// 切换单个商品选中
					this.cartList[index].dtsCart[goodsIndex].checked = !this.cartList[index].dtsCart[goodsIndex].checked;
				} else {
					// 全选逻辑
					const checked = !this.allChecked;
					this.cartList.forEach(brand => {
						brand.checked = checked;
						brand.dtsCart.forEach(goods => {
							goods.checked = checked;
						});
					});
					this.allChecked = checked;
				}
				this.calcTotal();
			},
			// 增加数量
			increaseQuantity(id) {
				const goods = this.findGoodsById(id);
				if (goods) {
					const oldValue = goods.number;
					goods.number++;
					this.updateQuantityOnServer(id, goods.number, oldValue);
					this.calcTotal();
				}
			},
		
			// 减少数量
			decreaseQuantity(id) {
				const goods = this.findGoodsById(id);
				if (goods && goods.number > 1) {
					const oldValue = goods.number;
					goods.number--;
					this.updateQuantityOnServer(id, goods.number, oldValue);
					this.calcTotal();
				}
			},
		
			// 根据ID查找商品
			findGoodsById(id) {
				for (const brand of this.cartList) {
					for (const goods of brand.dtsCart) {
						if (goods.id === id) return goods;
					}
				}
				return null;
			},
		
			//数量
			async updateQuantityOnServer(id, newVal, oldVal) {
				try {
					const res = await getCartUpdate({ id, number: newVal });
					if (res.data.code !== 200) {
						this.rollbackQuantity(id, oldVal);
						this.$message.error('更新失败: ' + (res.data.msg || ''));
					}
				} catch (error) {
					this.rollbackQuantity(id, oldVal);
					this.$message.error('网络错误');
				}
			},
		// 回滚数量
			rollbackQuantity(id, oldVal) {
				const goods = this.findGoodsById(id);
				if (goods) goods.number = oldVal;
				this.calcTotal();
			},
		
			// 输入框实时处理
			onQuantityInput(e, id) {
				const value = e.detail.value;
				let num = parseInt(value) || 1;
				num = Math.max(1, num);
				
				const goods = this.findGoodsById(id);
				if (goods) {
					goods.number = num;
					this.debounceUpdate(id, num);
				}
			},
		
			// 失焦处理
			handleInputQuantity(e, id) {
				const value = e.detail.value;
				let num = parseInt(value) || 1;
				num = Math.max(1, num);
				
				const goods = this.findGoodsById(id);
				if (goods) {
					const oldVal = goods.number;
					goods.number = num;
					this.updateQuantityOnServer(id, num, oldVal);
					this.calcTotal();
				}
			},
		
			// 防抖更新
			debounceUpdate(id, num) {
				clearTimeout(this.debounceTimer);
				this.debounceTimer = setTimeout(() => {
					const goods = this.findGoodsById(id);
					if (goods && goods.number === num) {
						this.updateQuantityOnServer(id, num, num);
					}
				}, 800);
			},

			//清空
			clearCart() {
				uni.showModal({
					content: '清空购物车？',
					success: (e) => {
						if (e.confirm) {
							this.cartList = [];
						}
					}
				})
			},
			//计算总价
			calcTotal() {
				let total = 0
				let allChecked = true

				this.cartList.forEach(brand => {
					let brandChecked = true
					brand.dtsCart.forEach(goods => {
						if (goods.checked) {
							total += Number(goods.price) * goods.number
						}
						if (!goods.checked) brandChecked = false
					})
					brand.checked = brandChecked
					if (!brandChecked) allChecked = false
				})

				this.allChecked = allChecked
				this.total = Number(total.toFixed(2))
			},

			//创建订单
			createOrder() {
			    // 验证是否有选中商品
			        if (!this.hasCheckedItems) {
			            return this.$api.msg('请选择要结算的商品');
			        }
			    
			        // 按品牌重组选中商品
			        const brandGroups = this.cartList
			            .filter(brand => 
			                brand.dtsCart.some(goods => goods.checked)
			            )
			            .map(brand => ({
			                name: brand.name,
			                goods: brand.dtsCart
			                    .filter(goods => goods.checked)
			                    .map(goods => ({
			                        id: goods.id,
									userId : goods.userId,
			                        goodsId: goods.goodsId,
			                        goodsName: goods.goodsName,
			                        price: goods.price,
			                        number: goods.number,
			                        picUrl: goods.picUrl,
			                        productId: goods.productId,
									specifications : goods.specifications,
			                        goodsSn: goods.goodsSn,
									brandId : goods.brandId
			                    }))
			            }));
						
						console.log("数据结构：" + JSON.stringify(brandGroups, null, 2));
			    
			        // 跳转到订单创建页
			        uni.navigateTo({
			            url: `/pages/order/createOrder?data=${encodeURIComponent(JSON.stringify({
			                brands: brandGroups,  // 使用分层结构
			                total: this.total
			            }))}`
			        });
			}
		}
	}
</script>

<style lang='scss'>
	page,
	.container {
		background: $page-color-base;
		height: 100%;
	}

	.container {
		padding-bottom: 134upx;

		/* 空白页 */
		.empty {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: 100vh;
			padding-bottom: 100upx;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			background: #fff;

			image {
				width: 240upx;
				height: 160upx;
				margin-bottom: 30upx;
			}

			.empty-tips {
				display: flex;
				font-size: $font-sm+2upx;
				color: $font-color-disabled;

				.navigator {
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}

	/* 购物车列表项 */
	.cart-item {
		display: flex;
		flex-direction: column;
		padding-left: 30upx;
		background: #fff;
		margin-top: 20px;
	}

	.goodsview {
		margin-top: 10px;
	}

	.goods-info {
		width: 250px;
		float: right;
		margin-right: 15px;
	}

	.goods-name {
		font-size: 15px;
		width: 240px;
		display: inline-block;
	}

	.price-and-num {
		display: inline-block;
		margin-top: 20px;
		font-size: 15px;
		width: 240px;
	}

	.goods-attr {
		float: right;
	}

	.checkbox {
		left: -16upx;
		top: -16upx;
		z-index: 8;
		font-size: 44upx;
		line-height: 1;
		padding: 4upx;
		color: $font-color-disabled;
		background: #fff;
		border-radius: 50px;
	}

	/* 新增样式 */
	.edit-bar {
		padding: 20upx 30upx;
		background: #fff;
		border-bottom: 1px solid #eee;
		width: 100%;
		height: 40px;

		.edit-btn {
			color: $uni-color-primary;
			font-size: 14px;
			float: right;
		}
	}

	.num-container {
		position: relative;
		min-width: 80upx;

		.static-num {
			position: absolute;
			right: 0;
			bottom: 0;
			color: #666;
		}
	}

	.left-group {
		flex: 1;
		display: flex;
		align-items: center;

		.select-all {
			margin-left: 10upx;
			font-size: 12px;
			color: #666;
		}
	}

	.number-box{
		z-index: 10;
	}
	/*数字组件，删除按钮*/
	.number-box{
		display: inline-block;
		width: 140px;
		height: 30px;
		line-height: 30px;
		background-color: #fff;
		position: absolute;
		left: 70px;
		bottom: 1px;
	}
	.number-box .quantity-input{
		display: inline-block;
		width: 40px;
		height: 30px;
		font-size: 20px;
		line-height: 30px;
		text-align: center;
	}
	.number-box .jian,.jia{
		display: inline-block;
		text-align: center;
		width: 50px;
		height: 30px;
		line-height: 30px;
		font-size: 20px;
		border: 0.5px solid #666;
		position: relative;
		bottom: 9px;
	}
	
	.goods-item {
		position: relative;
		padding: 20upx 0;

		.delete-btn {
			position: absolute;
			right: 20upx;
			bottom: 20upx;
			color: #ff4444;
			font-size: 12px;
			padding: 4upx 12upx;
			border: 1px solid #ff4444;
			border-radius: 8upx;
		}

		.price-and-num {
			position: relative;
			padding-bottom: 40upx;
		}
	}

	::v-deep .uni-numbox {
		height: 50upx !important;

		.uni-numbox__minus,
		.uni-numbox__plus {
			width: 50upx !important;
			height: 50upx !important;
			line-height: 50upx !important;
		}

		.uni-numbox__value {
			height: 50upx !important;
			line-height: 50upx !important;
		}
	}

	/* 店铺标题 */
	.i-top b-b{
		margin-top: 20px;
	}
	
	.shop-name {
		font-size: 16px;
		font-weight: bold;
		margin-left: 10px;
	}

	/* 商品复选框 */
	.goods-checkbox {
		width: 20px;
		height: 20px;
		border: 1px solid #ccc;
		border-radius: 50%;
		margin-right: 10px;

		&.checked {
			background: $uni-color-primary;
			border-color: $uni-color-primary;
		}
	}

	/* 商品项布局 */
	.goods-item {
		display: flex;
		align-items: center;

	}


	/* 底部栏 */
	.action-section {
		/* #ifdef H5 */
		margin-bottom: 100upx;
		/* #endif */
		position: fixed;
		left: 30upx;
		bottom: 30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 690upx;
		height: 100upx;
		padding: 0 30upx;
		background: rgba(255, 255, 255, .9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		border-radius: 16upx;
		justify-content: space-between;

		.checkbox {
			height: 52upx;
			position: relative;

			image {
				width: 52upx;
				height: 100%;
				position: relative;
				z-index: 5;
			}
		}

		.clear-btn {
			position: absolute;
			left: 26upx;
			top: 0;
			z-index: 4;
			width: 0;
			height: 52upx;
			line-height: 52upx;
			padding-left: 38upx;
			font-size: $font-base;
			color: #fff;
			background: $font-color-disabled;
			border-radius: 0 50px 50px 0;
			opacity: 0;
			transition: .2s;

			&.show {
				opacity: 1;
				width: 120upx;
			}
		}

		.total-box {
			flex: 1;
			display: flex;
			flex-direction: column;
			text-align: right;
			padding-right: 40upx;

			.price {
				font-size: $font-lg;
				color: $font-color-dark;
			}

			.coupon {
				font-size: $font-sm;
				color: $font-color-light;

				text {
					color: $font-color-dark;
				}
			}
		}

		.confirm-btn {
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			font-size: $font-base + 2upx;
			background: $uni-color-primary;
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72)
		}

		.batch-delete {
			padding: 0 20upx;
			margin-left: 90px;
			height: 76upx;
			line-height: 76upx;
			color: #ff4444;
			font-size: $font-base;
			border: 1px solid #ff4444;
			border-radius: 100px;
		}
	}

	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked {
		color: $uni-color-primary;
	}
</style>